package com.wjs.myspring.factory;

import com.wjs.myspring.dao.HelloDao;
import com.wjs.myspring.dao.imp.HelloDaoImp;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class BeanFactory {
    public static Properties properties;
    //缓存
    public static Map<String,Object> cache=new HashMap<>();

    static {
        properties=new Properties();
        try {
            properties.load(BeanFactory.class.getClassLoader().getResourceAsStream("factory.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static Object getDao(String beanName){
        if(!cache.containsKey(beanName)) {
            synchronized (BeanFactory.class) {
                try {
                    if (!cache.containsKey(beanName)) {
                        String value = properties.getProperty(beanName);
                        Class clazz = Class.forName(value);
                        Object instance = clazz.getConstructor().newInstance();
                        cache.put(beanName, instance);
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
        }
        return cache.get(beanName);
    }
}
